package com.guoguo.filter;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.BaseFilter;
import com.guoguo.base.StaticResource;
import com.guoguo.enums.UsersEnum;
import com.guoguo.utils.AuthorityValidateUtils;
import com.guoguo.utils.JsonUtils;
import com.guoguo.utils.RedisUtils;
import com.guoguo.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

/**
 * 权限验证过滤器
 * Created by Administrator on 2017/8/18 0018.
 */
public class AuthorityValidateFilter extends BaseFilter {

    private Logger log = LoggerFactory.getLogger(AuthorityValidateFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 权限验证
     *
     * @param servletRequest
     * @param servletResponse
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        JSONObject jsonObject = null;

        RedisUtils redisUtils = RedisUtils.getInstance();
        String field = request.getRequestURI();

        //从缓存里获得拥有权限url
        Iterator<String> purviewUrls = redisUtils.hkeys(StaticResource.SYS_INIT_PURVIEW_KEY).iterator();
        String permission = new String();
        boolean flag = false;
        while (purviewUrls.hasNext()) {
            String purviewUrl = purviewUrls.next();
            //判断url的权限
            if (StringUtils.match(purviewUrl, field, 0, 0)) {
                flag = true;
                //根据匹配的url去redis里获得权限信息
                permission = redisUtils.hget(StaticResource.SYS_INIT_PURVIEW_KEY, purviewUrl);
                break;
            }
        }
        int appId = request.getHeader("appId") == null ? 0 : Integer.valueOf(request.getHeader("appId"));
        //当前url是否有权限,
        if (flag) {
            //验证是否有权限
            if (AuthorityValidateUtils.validate(permission)) {
                HttpSession session = request.getSession();
                //session里如果没有权限的话，则获取权限集合，并保存到session里。
                if (session.getAttribute("roles") == null) {
                    String roleName = String.valueOf(session.getAttribute("roleName"));
                    //获得权限集合
                    JSONObject roles = AuthorityValidateUtils.getAuthority(permission);
                    //将权限集合保存到session里
                    session.setAttribute("roles", roles);
                }
                chain.doFilter(request, response);
            } else {
                //权限验证失败
                jsonObject = JsonUtils.returnObject(UsersEnum.AUTHORITY_VALIDATE_ERROR.getId(), "", UsersEnum.AUTHORITY_VALIDATE_ERROR.getValue());
                requestFailedSolution(appId, jsonObject, response);
            }
        } else {
            jsonObject = JsonUtils.returnObject(UsersEnum.AUTHORITY_VALIDATE_URL_ILLEGAL.getId(), "", UsersEnum.AUTHORITY_VALIDATE_URL_ILLEGAL.getValue());
            requestFailedSolution(appId, jsonObject, response);
        }
    }

    @Override
    public void destroy() {

    }
}
